package com.hty.batterymonitor;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.widget.RemoteViews;

public class WidgetService extends Service {
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		registerReceiver(BR, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	}

	private int getStateIcon(int batteryHealth) {
		if (batteryHealth >= 0 || batteryHealth <= 100)
			return MainApplication.batteryStateIcon[batteryHealth];
		return R.drawable.stat_sys_battery_unknown;
	}

	BroadcastReceiver BR = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int level = intent.getIntExtra("level", 0);
			int scale = intent.getIntExtra("scale", 100);
			int status = intent.getIntExtra("status", 0);
			int batteryHealth = level * 100 / scale;

			AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
			RemoteViews widgetView = new RemoteViews(context.getPackageName(), R.layout.monitor_widget_layout);

			if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
				widgetView.setImageViewResource(R.id.chargeico,	R.drawable.charge);
			} else {
				widgetView.setImageViewResource(R.id.chargeico,	R.drawable.tm);
			}
			widgetView.setImageViewResource(R.id.monitor_widget_view, getStateIcon(batteryHealth));
			widgetManager.updateAppWidget(new ComponentName(context, WidgetProvider.class), widgetView);
		}
	};

}